package com.example.show_auto.ui.pages

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.show_auto.ui.utils.OppoCompatibilityFix
import com.example.show_auto.viewmodel.MainViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.runtime.collectAsState

/**
 * 桌子收益数据项
 */
data class TableProfitItem(
    val id: Int,
    val suitName: String,
    val origin: String,
    val averageProfit: Double,
    val dailyMin: Double,
    val dailyMax: Double,
    val days: Double,
    val rank: Int,
    val unit: String = "玉璧/天"
)

/**
 * 根据秒数计算天数
 * 规则：
 * - 不足1天 → 1天
 * - 不足2天但小时数>12小时 → 2天
 * - 不足2天但小时数≤12小时且不为0 → 1.5天
 * - 不足2天但小时数=0 → 整天数
 * - 其他情况：剩余小时数>12小时算整天，≤12小时且不为0算半天，=0算整天
 */
private fun calculateDaysFromSeconds(seconds: Int): Double {
    val totalHours = seconds / 3600.0  // 转换为小时
    val fullDays = totalHours / 24.0   // 完整天数
    val remainingHours = totalHours % 24.0  // 剩余小时数
    
    return when {
        // 不足1天
        totalHours < 24.0 -> 1.0
        
        // 不足2天但小时数>12小时
        totalHours < 48.0 && remainingHours > 12.0 -> 2.0
        
        // 不足2天但小时数≤12小时且不为0
        totalHours < 48.0 && remainingHours <= 12.0 && remainingHours > 0.0 -> 1.5
        
        // 不足2天但小时数=0
        totalHours < 48.0 && remainingHours == 0.0 -> kotlin.math.floor(fullDays)
        
        // 其他情况按原逻辑
        remainingHours > 12.0 -> {
            // 剩余小时数 > 12小时，算作整天
            kotlin.math.ceil(fullDays)
        }
        remainingHours == 0.0 -> {
            // 剩余小时数 = 0，算作整天
            kotlin.math.floor(fullDays)
        }
        else -> {
            // 剩余小时数 ≤ 12小时且不为0，算作半天
            kotlin.math.floor(fullDays) + 0.5
        }
    }
}

/**
 * 根据天数返回显示文本
 */
private fun getDaysText(days: Double): String {
    return if (days % 1.0 == 0.0) {
        days.toInt().toString()
    } else {
        days.toString()
    }
}

/**
 * 桌子收益查询逻辑
 */
object TableProfitCalculator {
    fun calculateTableProfit(gameData: com.example.show_auto.data.GameData?): List<TableProfitItem> {
        if (gameData == null) return emptyList()
        
        // 获取装修数据
        val decorations = gameData.decorations
        
        // 根据origin字段分组
        val groupedByOrigin = decorations.groupBy { it.origin }
        
        val results = mutableListOf<TableProfitItem>()
        
        // 先计算所有结果，用于排名
        val allResults = mutableListOf<TableProfitItem>()
        
        groupedByOrigin.forEach { (origin, decorationList) ->
            // 只处理origin文字中带有"池"的分组
            if (origin.contains("池")) {
                // 取tipTime不为空且大于0的第一个桌子数据对象
                val tableDecoration = decorationList.firstOrNull { decoration ->
                    decoration.tipTime != null && decoration.tipTime > 0
                }
                
                tableDecoration?.let { decoration ->
                    val tipTime = decoration.tipTime ?: 0
                    val tipMin = decoration.tipMin ?: 0
                    val tipMax = decoration.tipMax ?: 0
                    
                    // 根据tipTime（秒）计算天数
                    val days = calculateDaysFromSeconds(tipTime)
                    
                    // 计算单天收益，每步都四舍五入保留一位小数
                    val dailyTipMin = kotlin.math.round((tipMin * 6.0 / days) * 10.0) / 10.0
                    val dailyTipMax = kotlin.math.round((tipMax * 6.0 / days) * 10.0) / 10.0
                    // 使用原始计算值来计算平均值，然后四舍五入
                    val rawDailyTipMin = tipMin * 6.0 / days
                    val rawDailyTipMax = tipMax * 6.0 / days
                    val averageProfit = kotlin.math.round(((rawDailyTipMin + rawDailyTipMax) / 2.0) * 10.0) / 10.0
                    
                    allResults.add(
                        TableProfitItem(
                            id = decoration.id,
                            suitName = decoration.suit,
                            origin = origin,
                            averageProfit = averageProfit,
                            dailyMin = dailyTipMin,
                            dailyMax = dailyTipMax,
                            days = days,
                            rank = 0, // 临时排名，稍后计算
                            unit = "玉璧/天"
                        )
                    )
                }
            }
        }
        
        // 计算排名：按平均收益降序排列，相同收益的按id降序排列，相同收益的排名相同
        val sortedResults = allResults.sortedWith(
            compareByDescending<TableProfitItem> { it.averageProfit }
                .thenByDescending { it.id }
        )
        var currentRank = 1
        var currentProfit = -1.0
        
        sortedResults.forEachIndexed { index, item ->
            if (item.averageProfit != currentProfit) {
                currentRank = index + 1
                currentProfit = item.averageProfit
            }
            // 更新排名
            val updatedItem = item.copy(rank = currentRank)
            results.add(updatedItem)
        }
        
        // 返回结果
        return results
    }
}

/**
 * 桌子收益查询结果页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TableProfitResultPage(
    onMenuClick: () -> Unit,
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    // 获取 ViewModel 和游戏数据
    val viewModel: MainViewModel = viewModel()
    val gameData by viewModel.gameData.collectAsState()
    val uiState by viewModel.uiState.collectAsState()
    
    // 下拉框状态
    var selectedDaysFilter by remember { mutableStateOf<String>("全部") }
    var isDropdownExpanded by remember { mutableStateOf(false) }
    
    // 搜索来源状态
    var originSearchText by remember { mutableStateOf<String>("") }
    
    // 查询已有状态
    var showOwnedOnly by remember { mutableStateOf(false) }
    
    // 列表状态，用于控制滚动
    val listState = rememberLazyListState()
    
    // 监听selectedDaysFilter、originSearchText和showOwnedOnly变化，滚动到顶部
    LaunchedEffect(selectedDaysFilter, originSearchText, showOwnedOnly) {
        listState.animateScrollToItem(0)
    }
    
    // 查询已有桌子的逻辑
    fun isTableOwned(origin: String, gameData: com.example.show_auto.data.GameData?): Boolean {
        if (gameData == null) return false
        
        // 根据桌子来源字段，查找菜谱为该来源的所有已拥有的菜谱
        val ownedRecipesCount = gameData.recipes.count { recipe ->
            recipe.origin == origin && recipe.got == true
        }
        
        // 如果数量大于5则表示是已拥有
        return ownedRecipesCount > 5
    }
    
    // 真实的桌子收益数据查询
    val allTableProfitData = remember(gameData) {
        TableProfitCalculator.calculateTableProfit(gameData)
    }
    
    // 找到ID最大的桌子
    val maxIdTable = remember(allTableProfitData) {
        allTableProfitData.maxByOrNull { it.id }
    }
    
    // 根据选择的天数和来源过滤数据，并过滤掉日均收益160以下的桌子
    val tableProfitData = remember(allTableProfitData, selectedDaysFilter, originSearchText, showOwnedOnly, gameData) {
        var filteredData = allTableProfitData.filter { it.averageProfit >= 160.0 }
        
        // 如果选择查询已有，则过滤出已拥有的桌子
        if (showOwnedOnly) {
            filteredData = filteredData.filter { item ->
                isTableOwned(item.origin, gameData)
            }
        }
        
        // 根据来源搜索过滤
        if (originSearchText.isNotEmpty()) {
            filteredData = filteredData.filter { item ->
                item.origin.contains(originSearchText, ignoreCase = true)
            }
        }
        
        if (selectedDaysFilter == "全部") {
            filteredData
        } else {
            // 从选择的天数文本中提取数值
            val daysText = selectedDaysFilter.replace("天桌", "")
            val targetDays = try {
                daysText.toDouble()
            } catch (e: NumberFormatException) {
                null
            }
            if (targetDays != null) {
                filteredData.filter { it.days == targetDays }
            } else {
                filteredData
            }
        }
    }
    

    
    // 获取所有天数类型（根据实际装修数据重新计算，过滤掉日均收益160以下的桌子）
    val daysOptions = remember(gameData) {
        val currentGameData = gameData
        if (currentGameData == null) {
            listOf("全部")
        } else {
            // 获取装修数据
            val decorations = currentGameData.decorations
            
            // 根据origin字段分组，只处理带有"池"的分组
            val groupedByOrigin = decorations.groupBy { it.origin }
            val allDays = mutableSetOf<Double>()
            
            groupedByOrigin.forEach { (origin, decorationList) ->
                if (origin.contains("池")) {
                    // 取tipTime不为空且大于0的第一个桌子数据对象
                    val tableDecoration = decorationList.firstOrNull { decoration ->
                        decoration.tipTime != null && decoration.tipTime > 0
                    }
                    
                    tableDecoration?.let { decoration ->
                        val tipTime = decoration.tipTime ?: 0
                        val tipMin = decoration.tipMin ?: 0
                        val tipMax = decoration.tipMax ?: 0
                        
                        // 使用calculateDaysFromSeconds重新计算天数
                        val days = calculateDaysFromSeconds(tipTime)
                        
                        // 计算单天收益
                        val dailyTipMin = kotlin.math.round((tipMin * 6.0 / days) * 10.0) / 10.0
                        val dailyTipMax = kotlin.math.round((tipMax * 6.0 / days) * 10.0) / 10.0
                        val averageProfit = kotlin.math.round(((dailyTipMin + dailyTipMax) / 2.0) * 10.0) / 10.0
                        
                        // 只添加日均收益>=160的天数
                        if (averageProfit >= 160.0) {
                            allDays.add(days)
                        }
                    }
                }
            }
            
            // 生成选项列表
            listOf("全部") + allDays.sorted().map { days ->
                if (days % 1.0 == 0.0) {
                    "${days.toInt()}天桌"
                } else {
                    "${days}天桌"
                }
            }
        }
    }

    OppoCompatibilityFix.FixedLayoutContainer(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部应用栏
        TopAppBar(
            title = { 
                Text(text = "桌子收益查询")
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(imageVector = Icons.Default.Menu, contentDescription = "菜单")
                }
            },
            actions = {
                IconButton(onClick = onBackClick) {
                    Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "返回")
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )

        // 页面内容
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(OppoCompatibilityFix.getFixedSpacing(16.dp)),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 筛选区域
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.Bottom
            ) {
                // 来源搜索框
                OutlinedTextField(
                    value = originSearchText,
                    onValueChange = { originSearchText = it },
                    label = { Text("搜索来源", fontSize = 12.sp) },
                    placeholder = { Text("输入桌子来源", fontSize = 12.sp) },
                    modifier = Modifier.weight(1f),
                    singleLine = true
                )
                
                // 天数过滤下拉框
                ExposedDropdownMenuBox(
                    expanded = isDropdownExpanded,
                    onExpandedChange = { isDropdownExpanded = it },
                    modifier = Modifier.width(100.dp)
                ) {
                    OutlinedTextField(
                        value = selectedDaysFilter.replace("桌", ""),
                        onValueChange = {},
                        readOnly = true,
                        label = { Text("桌子天数", fontSize = 12.sp) },
                        textStyle = androidx.compose.ui.text.TextStyle(fontSize = 12.sp),
                        trailingIcon = {
                            ExposedDropdownMenuDefaults.TrailingIcon(expanded = isDropdownExpanded)
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor()
                    )
                    
                    ExposedDropdownMenu(
                        expanded = isDropdownExpanded,
                        onDismissRequest = { isDropdownExpanded = false }
                    ) {
                        daysOptions.forEach { option ->
                            DropdownMenuItem(
                                text = { Text(option.replace("桌", ""), fontSize = 12.sp) },
                                onClick = {
                                    selectedDaysFilter = option
                                    isDropdownExpanded = false
                                }
                            )
                        }
                    }
                }
                
                // 查询已有按钮
                Button(
                    onClick = { 
                        showOwnedOnly = !showOwnedOnly
                    },
                    modifier = Modifier
                        .width(75.dp)
                        .height(65.dp)
                        .padding(top = 8.dp),
                    shape = RoundedCornerShape(4.dp),
                    contentPadding = PaddingValues(0.dp)
                ) {
                    Text(
                        text = if (showOwnedOnly) "查看全部" else "查看已有",
                        fontSize = 12.sp
                    )
                }
            }
            
            // 查询已有时的提示文字
            if (showOwnedOnly) {
                Text(
                    text = "已有数据根据来源估算判断，请以游戏内数据为准",
                    fontSize = 12.sp,
                    color = Color.Red,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.fillMaxWidth()
                )
            }

            // 结果列表
            LazyColumn(
                state = listState,
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(tableProfitData) { item ->
                    TableProfitItemCard(
                        item = item,
                        isLatest = maxIdTable?.id == item.id
                    )
                }
            }
            

        }
    }
}

/**
 * 桌子收益项目卡片
 */
@Composable
fun TableProfitItemCard(
    item: TableProfitItem,
    isLatest: Boolean = false,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // 第一行：套装名称和天数桌（两个字段）
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 左侧：套装名称
                Text(
                    text = item.suitName,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurface,
                    modifier = Modifier.weight(1f)
                )
                
                // 右侧：天数桌
                Text(
                    text = "${getDaysText(item.days)}天桌",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurface
                )
            }
            
            // 第二行：平均收益和日均最高最低
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 左侧：平均收益（只有数字部分绿色，去掉小数点后的0）
                val averageNumber = if (item.averageProfit % 1.0 == 0.0) {
                    item.averageProfit.toInt().toString()
                } else {
                    String.format("%.1f", item.averageProfit)
                }
                Row(
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "平均",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = averageNumber,
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = Color(0xFF4CAF50) // 绿色
                    )
                    Text(
                        text = item.unit,
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                // 右侧：日均最低/最高（红色/绿色，去掉小数点后的0）
                val dailyMinText = if (item.dailyMin % 1.0 == 0.0) {
                    item.dailyMin.toInt().toString()
                } else {
                    String.format("%.1f", item.dailyMin)
                }
                val dailyMaxText = if (item.dailyMax % 1.0 == 0.0) {
                    item.dailyMax.toInt().toString()
                } else {
                    String.format("%.1f", item.dailyMax)
                }
                Row(
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "日均最低/高",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = dailyMinText,
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = Color(0xFFE57373) // 红色
                    )
                    Text(
                        text = "/",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = dailyMaxText,
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = Color(0xFF4CAF50) // 绿色
                    )
                }
            }
            
            // 第三行：来源字段和排名
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "来源:${item.origin}",
                        fontSize = 12.sp,
                        color = Color.Gray,
                        fontStyle = androidx.compose.ui.text.font.FontStyle.Italic
                    )
                    if (isLatest) {
                        Text(
                            text = "（最新）",
                            fontSize = 12.sp,
                            color = Color.Blue,
                            fontWeight = FontWeight.Medium
                        )
                    }
                }
                Row(
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "全桌排名第",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = "${item.rank}",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Bold,
                        color = when {
                            item.rank <= 10 -> Color(0xFF4CAF50) // 绿色
                            item.rank <= 20 -> Color(0xFFFFC107) // 黄色
                            else -> Color(0xFFE57373) // 红色
                        },
                        modifier = Modifier.offset(y = 0.dp) // 
                    )
                }
            }
        }
    }
} 